import React from 'react';
import {parsePercent, safeMultiple, numberHandle} from '~/utils/number';

import CommonEchart from '../../common/CommonEchart';
import withPannel from './withPannel';
import {SELF_STACK_UNIT_ID, SELF_COLOR} from './color';

const tooltipCallback = params => {
    let html = '';
    let name = '';
    if (Array.isArray(params)) {
        html = params.map(entry => {
            const {
                marker,
                seriesName,
                data: {value = '', num = ''} = {},
                name: xAxisName
            } = entry;
            name = xAxisName;
            return `${marker}${seriesName} ${Number(num)} (${parsePercent(value, 2)})`;
        });
    }
    return `${name}<br/>${html.join('<br />')}`;
};

const labelFormatter = (params = {}) => {
    const {
        data: {value = 0} = {}
    } = params;
    return value ? parsePercent(value, 2) : '';
};

const handleOptions = ({legend, unitId}) => {
    let color;
    if (unitId === SELF_STACK_UNIT_ID && legend?.data?.length > 5) {
        color = SELF_COLOR[SELF_STACK_UNIT_ID];
    }
    const options = {
        color,
        tooltip: {
            trigger: 'axis',
            formatter: tooltipCallback
        },
        legend: {
            left: 'left'
        },
        xAxis: {
            common: {
                axisLabel: {
                    // rotate: 30
                }
            }
        },
        // revertXYAxis: true,
        yAxis: {
            newYAxis: [
                {
                    name: '',
                    type: 'value',
                    axisLabel: {formatter: value => `${safeMultiple(value, 100)}%`}
                }
            ],
            common: {
                splitLine: {show: false}
            }
        },
        grid: {
            left: 40,
            right: '3%',
            bottom: 20,
            containLabel: true
        },
        series: {
            common: {
                stack: '总量',
                barMaxWidth: 30,
                barGap: '100%',
                barCategoryGap: '50%',
                // label: {show: true, position: 'inside', formatter: labelFormatter}
            }
        }
    };
    return options;
};

const BarStackChart = props => {
    const {dataSource, unitId} = props;
    const {chart: {legend = {}} = {}} = dataSource || {};
    const extendOptions = handleOptions({legend, unitId});
    return (
        <CommonEchart
            {...props}
            id={unitId}
            extendEchartsOptions={extendOptions}
            dataSource={dataSource}
        />
    );
};

export default withPannel(BarStackChart);
